package dao;

import domain.Role;
import domain.Users;
import org.apache.ibatis.annotations.*;
import org.springframework.security.core.parameters.P;

import java.util.List;

/**
 * @author Freedy
 * @date 2020/12/25 17:14
 */
public interface IUserDao {

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     * @throws Exception
     */
    @Select("select * from users where username=#{username}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username",column = "username"),
            @Result(property = "email",column = "email"),
            @Result(property = "password",column = "password"),
            @Result(property = "phoneNum",column = "phoneNum"),
            @Result(property = "status",column = "status"),
            @Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(
                    select = "dao.IRoleDao.findRoleByUserId"
            ))
    })
    Users findByUserName(String username) throws Exception;

    /**
     * 查询所有用户
     * @return
     * @throws Exception
     */
    @Select("select * from users")
    List<Users> findAll() throws Exception;

    /**
     * 保存用户
     * @param users
     * @throws Exception
     */
    @Insert("insert into users(email,username,password,phoneNum,status)" +
            " values(#{email},#{username},#{password},#{phoneNum},#{status})")
    void save(Users users) throws Exception;

    /**
     * 根据id查询用户,并查询角色与权限
     * @param id
     * @return
     * @throws Exception
     */
    @Select("select * from users where id=#{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username",column = "username"),
            @Result(property = "email",column = "email"),
            @Result(property = "password",column = "password"),
            @Result(property = "phoneNum",column = "phoneNum"),
            @Result(property = "status",column = "status"),
            @Result(property = "roles",column = "id",javaType = java.util.List.class,many = @Many(
                    select = "dao.IRoleDao.findRoleByUserId"
            ))
    })
    Users findById(String id) throws Exception;

    /**
     * 查询可用role
     * @param userId
     * @return
     * @throws Exception
     */
    @Select("select * from role where id not in (select roleId from users_role" +
            " where userId = #{userId})")
    List<Role> findUserByIdAndAllRole(String userId) throws Exception;

    /**
     * 中间表添加关联
     * @param userId
     * @param roleId
     * @throws Exception
     */
    @Insert("insert into users_role(userId,roleId) values(#{userId},#{roleId})")
    void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId) throws Exception;
}
